<template>
	<view>
		<!-- <ls-loading :text="msgts" :animation="animation" v-if="pageLoading" :fontSize="36"></ls-loading> -->
		
		<view style="display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh"><image style="width: 30px;
    height: 30px;
    opacity: 0.15;
}" src="../../static/icon/load2.gif" v-if="pageLoading"></image></view><!-- <view class="loader" v-if="pageLoading"></view> -->
		<view v-if="is_show">
		<view v-if="yuan===true">
			<view class="flex p-xs padding ">
				<view class="flex-twice margin-xs">
					<view class="text-xl">{{bkdata.name}}</view>
					<view class="margin-top">{{bkdata.author}}</view>
					<view class="text-grey margin-top-sm">
						<text>{{bkdata.sort}}</text>
						<!-- <text class="margin-left-sm">{{bkdata.state}}</text> -->
					</view>
					<view class="margin-top">{{bkdata.time}}</view>
					<view class="margin-top">{{$t('book.ly')}}:{{bkdata.source_name}}<text class="jh"
							@click="onChange()">{{$t('book.hy')}}</text></view>
				</view>
				<view class="flex-sub margin-xs">
					<image :src="bkdata.img" mode="widthFix" class="radius img-box" lazy-load></image>
				</view>
			</view>
			<view v-if="config.c_ad && config.ad_status">
				<gr-ad :data="config" :type="config.ad_status" :height="150" ref="ad"></gr-ad>
			</view>
			<scroll-view scroll-x class="bg-white nav" scroll-with-animation>
				<view class="cu-item" v-for="(item,index) in TabData" :key="index"
					:class="index==TabCur?'text-orange cur':''" @tap="tabSelect" :data-id="index">
					{{item}}
				</view>
			</scroll-view>
			
			<view class="bg-white padding solid-top margin-bottom" v-if="TabCur==1">

				{{$t('book.js')}}：{{bkdata.intro}}
			</view>
			
			<view class="bg-white solid-top margin-bottom" v-else>
				<ls-loading :text="msgts" :animation="animation" v-if="loging" :fontSize="28" :embed="true">
				</ls-loading>
				<view v-else>
					<view class="cu-bar solid-bottom">
						<view class="action">
							<text class="text-sm">{{$t('book.gxz')}}{{bkdata.news}}</text>
						</view>
						<view @click="orderClick" style="margin-right:30rpx;color: #F44336;"><label class="iconfont">&#xe618;</label> {{order}}</view>
					</view>
				<!-- 	<view class="cu-list menu" v-if="listData">
						<text class="cu-item arrow" v-for="(item,index) in listData" :key="item.id"
							@click="details(item,item.id,index)">
							{{item.name}}
						</text>
					</view> -->
					<virtual-list :items="listData" :size="40" :remain="16" :active="0" :scrollHeight="500"  >
						<template v-slot="{item,active}">
							<view @click="details(item,item.id,index)" class="cu-item arrow">
									{{item.name}}
							</view>
						</template>
					</virtual-list>  
				</view>
				
			</view>
			<view class="cu-tabbar-height"></view>
			<view class="cu-bar bg-white tabbar border zai-tabbar-bar" v-if="listData.length>0">
				<view class="btn-group">
					<button class="cu-btn bg-orange round shadow-blur" @click="AddClick"
						v-if="addBtn==false">{{$t('book.jrsj')}}</button>
					<text v-else>{{$t('book.yjrsj')}}</text>
				</view>
				<view class="btn-group">
					<button class="cu-btn bg-red round shadow-blur" @click="wxad()">{{$t('book.ljyd')}}</button>
				</view>
			</view>

			<wyb-popup ref="popup" type="center" radius="6" :showCloseIcon="false" :scrollY="true" height="800" width="600">
				<view class="yuanba">
					<view class="text-xl">{{bkdata.name}}</view>
					<view class="margin-top">{{bkdata.author}}</view>

				</view>

				<view class="cu-list menu">

					<view class="cu-item " v-for="(item,index) in Bookdata.list" :key="item.id" @click="qieyuan(item)">
						<view>
							<view class="yuanname">{{item.name}}</view>
							<view> {{item.source.book_name}}{{item.author?'_'+item.author:item.author}}</view>
						</view>
						<view v-show="item.source.book_name==bkdata.source_name && bkdata.author==(item.author?item.author:bkdata.author)">✓</view>
					</view>


					
				</view>

			</wyb-popup>


		</view>
		<view v-else>
			
			<view v-if="config.c_ad && config.ad_status">
				<gr-ad :data="config" :type="config.ad_status" :height="150" ref="ad"></gr-ad>
			</view>
			<view style="text-align: center;margin-top: 200rpx;">
				<!-- #ifdef MP || H5 -->
				未检索到本书内容
				</navigator>
				</navigator>
				<!-- #endif -->
				<!-- #ifdef APP-PLUS -->
				未检索到书源请添加小说规则 请 <navigator :url="'/pages/user/yuanlist'" animation-type="pop-in">
					<font style="color:red">配置规则</font>
				</navigator>
				<!-- #endif -->
			</view>
		
		</view>
<xy-dialog 
		    title="提示"
		    :show="isshow"
		    @cancelButton="clickCancel"
		    @confirmButton="clickConfirm"
			@close="clickclose">
		    <view style="padding: 0 30upx 30upx;">
		        <view>{{tname}}</view>
		       
		    </view>
		</xy-dialog>
		</view>
	</view>
</template>

<script>
	let rewardedVideoAd = null //激励视频
	// 在页面中定义激励视频广告
	let interstitialAd = null //激励调用
	import virtualList from '@/components/virtualList.vue'
	import _pc from '@/util/pc.js';
	import _tool from '@/util/tools.js';
	// #ifdef  APP-PLUS
	import _sql from '@/util/sql.js';
	// #endif
	import wybPopup from '@/components/wyb-popup/wyb-popup.vue'
	import time from '@/util/getdateTime.js';
import xyDialog from '@/components/xy-dialog/xy-dialog.vue';
	export default {
		components: {
			wybPopup,
			xyDialog,
			virtualList
		},
		data() {
			return {
				isshow:false,
				is_show:false,
				pageLoading: true,
				loging: true,
				animation: 'twinkle',
				TabCur: 0,
				config: {},
				msgts:this.$t('book.sjyzq'),
				TabData: [this.$t('book.zj'), this.$t('book.js')],
				bkdata: {},
				listData: [],
				order: this.$t('book.up'),
				BookID: null,
				addBtn: true,
				newsID: null,
				newsName: '',
				Bookdata: {},
				key: '',
				author:'',
				sqllist: [],
				yuan: true,
				limit: 0,
				isbook: 0,
				author: '',
				sors: {},
				zhong:0,
				adis:0,
				isad:0,
				tt:0,
				ydus:0,
				tname:'',
				adyujiazai:0,
				loading: false,
				listcacheData:[],
				 currentPage: 1, // 当前页数
				 pageSize:1000, // 每页数据条数
				
			}
		},
		onShow() {
			if(!this.pageLoading){
				uni.navigateBack({
				    delta: 1 // 返回上一页，如果需要返回多级页面，可以设置为更大的数字
				  });
			}
			_pc.system()
			// #ifdef  APP-PLUS
			let _this = this;
			_sql.selectSQL("select * from " + this.dbs + " where book_state=1").then(function(res) {
				if (res.length > 0) {
					_this.sqllist = res
					_this.yuan = true;
				} else {
					_this.yuan = false;
				}
			});
			// #endif 
			// #ifdef  MP
			
			// #endif 

		},
		onShareTimeline() {
			return {
				title: this.bkdata.name,
				query: '/pages/book_mall/details?type=list&name=' + this.bkdata.name,
				imageUrl: this.bkdata.img
			}
		},
		onShareAppMessage(res) {

			return {
				title: this.bkdata.name,
				path: '/pages/book_mall/details?type=list&name=' + this.bkdata.name
			}
		},

		onLoad(option) {
			// 在页面中定义插屏广告
			var _this = this;
			this.config = uni.getStorageSync('config');
				console.log(option)

			// #ifdef  MP
			this.sqllist =uni.getStorageSync('shuyuan1')
			console.log(this.sqllist)
			// 在页面onLoad回调事件中创建插屏广告实例
			if (wx.createInterstitialAd && this.config.wx_ad_ys_cp && parseInt(this.config.task_wx_status_j)) {
				interstitialAd = wx.createInterstitialAd({
					adUnitId: this.config.wx_ad_ys_cp
				})
				interstitialAd.onLoad(() => {})
				interstitialAd.onError((err) => {})
				interstitialAd.onClose(() => {})
			}
			// #endif 



			if (option.type === 'list') {
				this.pageLoading = true;
				this.key = option.name
				this.author = option.author
			
				if (_this.key) {
					// #ifdef  MP
					if (this.sqllist.length > 0) {

						_this.searchBtn(0)
					} else {
						_this.pageLoading = true;
						_this.yuan = false;
					}
					// #endif 
					// #ifdef  APP-PLUS
					_sql.selectSQL("select * from " + this.dbs + " where book_state=1").then(function(res) {

						if (res.length > 0) {

							_this.sqllist = res
							_this.searchBtn(0)
						} else {
							_this.pageLoading = false;
							_this.yuan = false;
						}
					});
					// #endif 
				}
			} else {

				// #ifdef  MP
				if (_this.sqllist.length > 0) {

					this.pageLoading = false
					this.BookID = option.id;
					this.Bookdata = uni.getStorageSync('details' + option.id);
					this.key = option.name
					this.author = option.author
					_this.searchBtn(_this.Bookdata.source)
					this.bkdata.img = _this.Bookdata.img
					this.bkdata.source_name = _this.Bookdata.source.book_name
					this.bkdata.news = _this.bkdata.news
					this.bkdata.intro = _this.Bookdata.introduce
					
					this.bkdata.name = _this.Bookdata.name
					this.bkdata.author = _this.Bookdata.author
					this.bkdata.sort = _this.Bookdata.sort
					if (!this.bkdata.intro) {
						this.TabData = [this.$t('book.zj')]
					}
					this.boos(0);
				} else {
					_this.yuan = false;
				}
				// #endif 

				// #ifdef  APP-PLUS
				_sql.selectSQL("select * from " + this.dbs + " where book_state=1").then(function(res) {

					if (res.length > 0) {
						_this.sqllist = res
						_this.pageLoading = false
						_this.BookID = option.id;
						_this.Bookdata = uni.getStorageSync('details' + option.id);
						_this.bkdata.img = _this.Bookdata.img
						_this.bkdata.source_name = _this.Bookdata.source.book_name
						_this.bkdata.news = _this.bkdata.news
						_this.bkdata.intro = _this.Bookdata.introduce
						_this.bkdata.name = _this.Bookdata.name
						_this.bkdata.author = _this.Bookdata.author
						_this.bkdata.sort = _this.Bookdata.sort
						_this.searchBtn(_this.Bookdata.source)
						if (!_this.bkdata.intro) {
							_this.TabData = [_this.$t('book.zj')]
						}
						_this.boos(0);
					} else {
						_this.yuan = false;
					}
				});
				// #endif
			}

			if (this.config.ad_status) {
				this.$nextTick(() => {
					_this.$refs.ad.update_ad()
				})
			}



		},
		onReady() {
			// #ifdef   APP-PLUS
			this.config = uni.getStorageSync('config');
			// 在页面onLoad回调事件中创建插屏广告实例
			this.createInterstitialAd();	
			// 创建广告实例
			if(parseInt(this.config.ad_status)==2 && this.config.app_ad_ys_cp){
				
			}
			// #endif 
			this.jlad()
			//this.wxad()
		},
		
		onHide() {
			// #ifdef  MP
			if (this.zhong) {
				uni.setStorageSync('adis',1)
				if(this.adis){
					this.adis =1
				}else{
				this.adis = this.adis++
				}
				
			}
			// #endif 
		},
		 onUnload() {
		// #ifdef  MP
		console.log('我点击了广告',this.zhong)
		
		// #endif 
		      // 页面关闭后销毁实例
		if(this.interstitialAd){
		      this.interstitialAd.destroy()
		}
		},
		methods: {
			jlad(bkdata) {
				let _this = this;
				if (wx.createRewardedVideoAd) {
					rewardedVideoAd = wx.createRewardedVideoAd({
						adUnitId: _this.config.wx_ad_jl
					})
					rewardedVideoAd.onLoad(() => {
						console.log('onLoad event emit')
						_this.adis = 0
						_this.adyujiazai = 0
					})
					rewardedVideoAd.onError((err) => {
						console.log('onError event emit', err)
						_this.adis = 0
						_this.adyujiazai = 0
						uni.showToast({
							icon: 'none',
							title: '当前未获取到广告资源，请稍后再试',
							duration: 2000
						});
			
					})
					rewardedVideoAd.onClose((res) => {
						// 用户点击了【关闭广告】按钮
			
			
						if (res && res.isEnded) {
							_this.adyujiazai++;
							_this.ydus = 1
							console.log('this.adis',_this.adis,uni.getStorageSync('adis'))
							//_this.zhong = 1;
							if(_this.zhong){
							_this.zengjia()
							}else{
							setTimeout(()=>{
								_this.readClick()	
							},1500)
							}
							console.log('正常播放结束，可以下发游戏奖励',_this.adyujiazai)
							// 正常播放结束，可以下发游戏奖励
						} else {
							console.log('guang',_this.zhong)
							_this.adis = 0
							_this.adyujiazai = 0;
			// 				if (_this.adis && _this.zhong) {
			// 					if(_this.zhong!=2){
			// 					uni.showToast({
			// 						icon: 'none',
			// 						title: '中途关闭了广告，无法为您获取权限！',
			// 						duration: 2000
			// 					});
			// 					}
			
			// 				} else {
			// 					if(_this.zhong!=2){
			// 					uni.showToast({
			// 						icon: 'none',
			// 						title: '中途关闭了广告，无法为您获取权限!',
			// 						duration: 2000
			// 					});
			// 					}
			
			// 				}
							_this.adyujiazai = 0
							// 播放中途退出，不下发游戏奖励
							//_this.readClick()
						}
					})
			
				}
			
			
				// 在页面onLoad回调事件中创建插屏广告实例
				if (wx.createInterstitialAd) {
					interstitialAd = wx.createInterstitialAd({
						adUnitId: this.config.wx_ad_ys_cp
					})
					interstitialAd.onLoad(() => {})
					interstitialAd.onError((err) => {})
					interstitialAd.onClose(() => {})
				}
			},clickCancel(e){
				this.isshow=!this.isshow
				uni.setStorageSync('urlxxa', this.config.book_source_list);
				
				uni.navigateTo({
					url: '/pages/about/url' 
				})
				console.log('点击了1',e)
			},
			clickclose(){
				this.isshow=!this.isshow
			},
			clickConfirm(e){
				this.isshow=false
				
				
				// #ifdef  MP
				var _this = this;
				_this.readClick()
					
					rewardedVideoAd.show().then(() => {
						console.log('激励视频 广告显示')
					}).catch(err => {
						// uni.showToast({
						// 	icon: 'none',
						// 	title: '当前未获取到广告资源，2秒后开启阅读',
						// 	duration: 2000
						// });
						// setTimeout(res => {
						// _this.readClick()
						// }, 2000)
						//_this.readClick()
					})
				
			// #endif 
				
			},
			showAd() {
			        // 调用后会显示 loading 界面
			        AD.show({
			          adpid:this.config.app_ad_jl, // HBuilder 基座测试广告位
			          adType: "RewardedVideo",
			          //singleton: false // 设置此参数后，每次调用 show 方法将重新创建广告实例，预载将失效，如果广告回调每次要透传用户信息需要设置 false
			        }, (res) => {
			          // 用户点击了【关闭广告】按钮
			          if (res && res.isEnded) {
			            // 正常播放结束
						this.zengjia()
			            console.log("onClose " + res.isEnded);
			          } else {
			            // 播放中途退出
			           if (this.adis && this.zhong) {
			           	uni.showToast({
			           		icon: 'none',
			           		title: '中途关闭了广告，无法为您免除广告时长',
			           		duration: 2000
			           	});
			           
			           
			           } else {
			           	uni.showToast({
			           		icon: 'none',
			           		title: '中途关闭了广告，无法为您免除广告时长',
			           		duration: 2000
			           	});
			           
			           }
			          }
			
			          // 在此处理服务器回调逻辑
			        }, (err) => {
			          // 广告加载错误
					  uni.showToast({
					  	title: '当前未获取到广告资源，请稍后再试',
						icon:'none',
					  	duration: 3000
					  });
			          console.log(err)
			        })
			      },
			wxad() {
				this.tt = parseInt(uni.getStorageSync('config_time'));
				console.log('sssssssssss',this.tt)
				if (this.tt < time.dtime()) {
					this.tt = 0
				}
				if(this.tt){
					this.readClick()
				}
				//this.adis = 1
				let sum = 0;
				let urls = [];
				for (let i = 0; i < 100 / parseInt(this.config.task_wx_statussj); i++) {
					urls.push(i+1);
				}
				var element = urls[Math.floor((Math.random() * urls.length))]
				//this.isshow=!this.isshow
				if (element === urls.length) {
					// uni.showToast({
					// 	icon: 'none',
					// 	title: this.config.task_wx_q_name,
					// 	duration: 2000
					// });
					uni.setStorageSync('adis',0)
					this.adis=0;
					this.tname=this.config.task_wx_q_name
					this.zhong = 1;
					//this.isshow=!this.isshow
					console.log('启动了强点', this.zhong)
				} else {
					this.tname=this.config.task_wx_b_name
					// uni.showToast({
					// 	icon: 'none',
					// 	title: this.config.task_wx_b_name,
					// 	duration: 2000
					// });
					this.zhong = 0;
					console.log('未启动强点', this.zhong)
					// setTimeout(res => {
					
					// 	rewardedVideoAd.show().then(() => console.log('激励视频 广告显示'))
					// }, 1000)
				}
				
			
			// #ifdef  APP-PLUS
			
			
			
			this.showAd()
			
			// #endif 
				// #ifdef  MP
				
				// setTimeout(res => {
				
				// 	rewardedVideoAd.show().then(() => console.log('激励视频 广告显示'))
				// }, 1000)
				// #endif
			this.clickConfirm()
				
			},
			zengjia() {
				console.log('this.adyujiazai', this.adyujiazai)
				if (this.adyujiazai > 2) {
					console.log('this.进去了', this.adyujiazai)
					this.isad = 0
					
					return;
			
				}
				this.config = uni.getStorageSync('config');
				this.tt = parseInt(uni.getStorageSync('config_time'));
				this.adis=this.adis?this.adis:uni.getStorageSync('adis');
				console.log('this.adis---',this.adis,uni.getStorageSync('adis'))
				console.log('this.tt',this.tt,this.adis,this.zhong,this.ydus)
				if (this.adis && this.zhong == 1 && this.ydus == 1) {
					uni.setStorageSync('adis',0)
					let times = this.tt ? (this.tt + parseInt(this.config.task_wx_status_j_time)) : parseInt(this.config
						.task_wx_status_j_time)
			
					if (this.tt < time.dtime()) {
						this.tt = 0
					}
					let st = this.tt ? time.timej(times, this.tt) : time.timej(times, 0)
					uni.setStorageSync('config_time', st);
					this.zhong = 0
					this.adis = 0
					this.isad = 0
					this.config.task_wx_status_j = 0;
					this.$forceUpdate()
				
					uni.showToast({
						icon: 'none',
						title: '成功获取24小时畅读权限！',
						duration: 2000
					});
					uni.$emit('ad_time')
					setTimeout(()=>{
						_this.readClick()	
					},1000)
				}
				if (this.zhong == 2) {
					console.log('中标判断----xxx---', this.zhong)
					let times = this.tt ? (this.tt + parseInt(this.config.task_wx_status_b_time)) : parseInt(this.config
						.task_wx_status_b_time)
			
					if (this.tt < time.dtime()) {
						this.tt = 0
					}
					let st = this.tt ? time.timej(times, this.tt) : time.timej(times, 0)
					uni.setStorageSync('config_time', st);
					this.zhong = 0
					this.adis = 0
					this.isad = 0
					this.config.task_wx_status_j = 0;
					this.$forceUpdate()
					
			
					uni.showToast({
						icon: 'none',
						title: '成功获取24小时畅读权限！',
						duration: 2000
					});
				}
			
				if (this.adis == 0 && this.zhong == 1) {
					this.zhong = 0
					this.adis = 0
					uni.showToast({
						icon: 'none',
						title: '未点击绿色按钮体验，24小时畅读权限获取失败！',
						duration: 6000
					});
				}
			
			
			},
			createInterstitialAd() {
				interstitialAd = this.interstitialAd = uni.createInterstitialAd({
					'adpid': this.config.app_ad_ys_cp?this.config.app_ad_ys_cp:this.app_ad_ys_cp
				});
				interstitialAd.onLoad(() => {
					this.loading = false;
					console.log("插屏 广告加载成功");
				});
				interstitialAd.onClose(() => {
					// 用户点击了关闭或返回键(仅Android有返回键)
					console.log("插屏 广告关闭");
				});
				interstitialAd.onError((err) => {
					this.loading = false;
					console.log("插屏 广告加载失败");
				});

				// 广告实例创建成功后默认会执行一次 load，加载广告数据
				// 如果界面有 "显示广告" 按钮，需要先禁用掉，防止用户点击，等待广告数据加载成功后在放开
				this.loading = true;
			},
			showInterstitialAd() {
				// 调用 interstitialAd.show()，如果数据正在加载中不会显示广告，加载成功后才显示
				// 在数据没有加载成功时，需要防止用户频繁点击显示广告
				if (this.loading == true) {
					return
				}
				this.loading = true;
				this.interstitialAd.show().then(() => {
					this.loading = false;
				});
			},
			xsd(x, y) {
				var z = 0;
				x = x.toUpperCase();
				y = y.toUpperCase();
				x = x.replace('_', '');
				y = y.replace('_', '');
				if (typeof x == "string") {
					x = x.split("");
					y = y.split("");
				}
				var s = x.length + y.length;
				x.sort();
				y.sort();
				var a = x.shift();
				var b = y.shift();
				while (a !== undefined && b != undefined) {
					if (a === b) {
						z++;
						a = x.shift();
						b = y.shift();
					} else if (a < b) {
						a = x.shift();
					} else if (a > b) {
						b = y.shift();
					}
				}
				return z / s * 200;
			},
			async searchBtn(data) {


				if (data) {
					
					this.sors = data
					this.GetBookDetails(this.BookID, 0)

				} else {
					var _this = this;
					if (_this.limit === this.sqllist.length) {
						this.pageLoading = false;
						this.yuan = false
						console.log('zhong')
						return
					} else {
						this.pageLoading = true;
					}
					if (this.sqllist.length > 0) {
						this.sors = this.sqllist[this.limit]
						this.so(this.sqllist[this.limit].search_url, this.sqllist[this.limit])

					}
				}
			},
			async so(search_url, data) {

				var _this = this;
				let url = search_url.replace("{{key}}",encodeURIComponent( _this.key));
				let arr = {};
				if (data.search_http === 'POST') {
					let code = url.split('?')[1]
					// url=url.split('?')
					arr = this.postsplic(code)
				}
				this.sors = data
				let header = {}
				if (data.header) {
					header = this.hesplic(data.header)
				}

				this.zaiApi({
					url: url,
					method: data.search_http,
					data: arr,
					header: header
				}).then(function(res) {
					_this.GetSearchData(res, data)
				}).catch(e => {
				console.log('------------')
				if(this.listcacheData.length<=0){
				_this.limit = _this.limit + 1;
				_this.searchBtn()
				}
				});
			},
			GetSearchData(res, data) {
				let _this = this;
				if (this.Bookdata) {
					_tool.searchData(res, data).then(function(ress) {

						if (ress.length === 0) {
							_this.limit = _this.limit + 1;
							//console.log('this.sqllist.length', _this.sqllist.length, _this.limit)
							_this.searchBtn()
						} else {
							let name = _this.key + _this.author
							ress.forEach((res) => {
								if (_this.xsd(res.name, _this.key) > 90 && (_this.author?_this.xsd(res.author, _this.author)>90 :true)) {
									_this.isbook = 0;
									_this.BookID = res.id
									_this.Bookdata = res;
									_this.boos(0);
									
								} else {
									_this.isbook++;
								}
							});

							if (ress.length === _this.isbook) {
								_this.isbook = 0;
								_this.limit = _this.limit + 1;
								_this.searchBtn()

							}


							// _this.searchBtn()
						}

					});
				}
			},
			boos(is) {
				let ids = is || 0
				this.GetBookDetails(this.BookID, ids);
				//是否已经加入书架
				_tool.GetBookListID(this.Bookdata.name).then((res) => {
					this.addBtn = res;
				});

			},
			watchClose() {

				this.$refs.popup.close();
			},
			qieyuan(e) {
				uni.showToast({
					title: this.$t('book.sjyqhz'),
					icon: 'none'
				});
				
				this.listData = []
				e.length = this.Bookdata.list.length
				e.list = JSON.stringify(this.Bookdata.list)
				e.list = JSON.parse(e.list)
				this.BookID = e.id;
				uni.setStorageSync('details' + this.BookID, e);
				this.Bookdata = e
				this.$refs.popup.close();
				this.loging=true
				this.msgts="换源数据处理中"
				this.boos(1);

			},
			tabSelect(e) {
				this.TabCur = e.currentTarget.dataset.id;
			},
			GetBookDetails(id, is) {

				let header = {}
				if (this.sors.header) {
					header = this.hesplic(this.sors.header)
				}
				let ids = is || 0
				let url = this.Bookdata.source.rand_url.replace("{{key}}", id);
					url=url.replace("$$",Math.round(parseInt(id)/1000)); //检索千分之一换算
				this.zaiApi({
					url: url,
					header: header
				}).then((res) => {
					
					this.GetDetailsData(res, ids)
				}).catch((err)=>{
					console.log('出错了',err.$t) 
					this.msgts='此书章节过多，加载可能需要1-3分钟...'
					if(this.listcacheData.length<=0){
					this.limit = this.limit + 1;
					this.searchBtn()
					}
					
				});
			},
			GetDetailsData(Book, is) {
				let _this = this;
			
				_tool.DetailsData(Book, _this.Bookdata.source, _this.BookID).then((res) => {
						
					res.list = this.iddecs(res.list)
					this.bkdata.id=res.data.id;
					this.BookID=res.data.id; 
					
					res.list.forEach((item, index) => {
						item.id = index
					})
					_this.listcacheData = JSON.parse(JSON.stringify(res.list));
					this.bkdata = res.data;
					this.bkdata.img = _this.Bookdata.img ? _this.Bookdata.img : res.data.img
					this.bkdata.name = _this.Bookdata.name ? _this.Bookdata.name : res.data.name
					this.bkdata.source_name = _this.Bookdata.source.book_name

					this.bkdata.news = _this.bkdata.news ? _this.bkdata.news : (res.list.length > 0 ? res
						.list[res.list
							.length - 1].name : 0)

					this.bkdata.intro = _this.Bookdata.introduce ? _this.Bookdata.introduce : res.data.intro
					
					this.bkdata.author = _this.Bookdata.author ? _this.Bookdata.author : res.data.author

					this.bkdata.sort = _this.Bookdata.sort ? _this.Bookdata.sort : res.data.sort

					if (!this.bkdata.intro) {

						this.TabData = [this.$t('book.zj')]

					}
					this.currentPage= 1, // 当前页数
					this.pageSize=1000, // 每页数据条数
					this.fetchData(res.list)
					
					if (res.list.length > 0) {
						_this.newsID = res.list[0].id;
						_this.newsName = res.list[0].name;
					}
					_this.bkdata = this.bkdata;
					_this.loging = false
					_this.pageLoading = false;
					
					if (is) {
						let bkdatas = {
							id: this.BookID,
							sid: 0,
							page: 0,
							index: 1,
							name: this.bkdata.name,
							title: this.bkdata.name,
							img: this.bkdata.img,
							data: this.Bookdata,
							list: []
						};
						this.setdatalist(this.listcacheData,this.BookID)	
						_tool.UpBookListData(bkdatas).then((res) => {

						});
					}
					setTimeout(res => {
						uni.hideLoading()
					}, 3000)
				});
			},
			fetchData(totalData) {
		      // 假设dataList为较大的数据数组，这里只是模拟
		      // 计算当前页的数据在总数据中的起始索引和结束索引
		      const start = (this.currentPage - 1) * this.pageSize;
		      const end = Math.min(start + this.pageSize, totalData.length);
			let _this=this
		      // 将当前页的数据更新到listData中
		      this.listData = this.listData.concat(totalData.slice(start, end));
		
		      // 更新当前页数
		      this.currentPage++;
		      // 如果还有剩余数据，继续下一次更新（使用nextTick确保页面渲染完成后再更新）
		      if (end < totalData.length) {
				  setTimeout(()=>{
					  _this.fetchData(totalData)
				  }, 0);
		      }else{
				  _this.wxad()
				  _this.yuan = true;
				  _this.loging = false
				  // _this.pageLoading = false;
				  // #ifdef  APP-PLUS
				  _this.showInterstitialAd()
				  	// #endif 
				  // #ifdef  MP
				  // 在适合的场景显示插屏广告
				  if (interstitialAd && _this.config.wx_ad_ys_cp && parseInt(_this.config.task_wx_status_j)) {
				  	interstitialAd.show().catch((err) => {
				  		//console.error(err)
				  	})
				  }
				  // #endif
			  }
			 
		    },
			orderClick() {
				let order = this.order;
				if (order == this.$t('book.up')) {
					this.order = this.$t('book.down');
				} else {
					this.order = this.$t('book.up');
				}
				//排序
				let desc = this.listData.reverse();
				// desc.forEach((item, index) => {
				// 	item.sort = item.id
				// })
				this.listData = desc
			},
			AddClick() {
				console.log(223)
				let bkdata = {
					id: this.BookID,
					sid: this.newsID,
					author: this.bkdata.author,
					page: 0,
					index: 1,
					name: this.bkdata.name,
					title: this.bkdata.name,
					img: this.bkdata.img,
					data: this.Bookdata,
					list: []
				};
				this.setdatalist(this.listcacheData,this.BookID)
				_tool.AddBookListData(bkdata).then((res) => {
					this.addBtn = true;
				});
			},
			readClick() {
				let obj=Object.entries(uni.getStorageSync('Bookindex')).length !== 0;
				let sid=obj?uni.getStorageSync('Bookindex').sid:0;
				let index=obj?uni.getStorageSync('Bookindex').index:0;
				
				let bkdata = {
					id: this.BookID,
					sid:sid,
					page: 0,
					index:index,
					name: this.bkdata.name,
					title: this.bkdata.name,
					img: this.bkdata.img,
					data: this.Bookdata,
					list:[]
				};
				
				try {
					if (this.listData.length <= 0) {
						uni.showToast({
							title: this.$t('book.qxzly'),
							icon: 'none'
						});
						return
					}
					this.setdatalist(this.listcacheData,this.BookID)
					uni.setStorageSync('BookReadData', bkdata);
					uni.setStorageSync('Bookindex', {});
					uni.navigateTo({
						url: '/pages/bookshelf/read'
					})
				} catch (e) {
					uni.showToast({
						title: this.$t('book.sjyc'),
						icon: 'none'
					});
				}
			},
			setdatalist(item,id){
				let listData=JSON.stringify(item)
				uni.removeStorageSync('book_list1'+id);
				uni.removeStorageSync('book_list2'+id);
				uni.setStorageSync('book_list1'+id, this.customTruncate(listData,1,0));
				uni.setStorageSync('book_list2'+id, this.customTruncate(listData,2,1048576));
			},
			details(item, index, key) {
				
				
				let order = this.order;
				let readId = index + 1;
				if (order == '正序') {
					let listId = this.listData.length;
					readId = listId - index - 1;
				}
				
				// 压缩对象
				let bkdata = {
					id: this.BookID,
					sid: index,
					page: 0,
					index: readId,
					name: this.bkdata.name,
					title: this.bkdata.name,
					img: this.bkdata.img,
					data: this.Bookdata,
					list:[]
				};
				
					if (this.listData.length <= 0) {
						uni.showToast({
							title: this.$t('qxzly'),
							icon: 'none'
						});
						return
					}
					let indexdata={
						id: this.BookID,
						sid: index,
						page: 0,
						index: readId
					}
					uni.setStorageSync('Bookindex', indexdata);
					uni.setStorageSync('BookReadData', bkdata);
					this.setdatalist(this.listcacheData,this.BookID)
					let tt = time.getInervalHour(time.dtime(), uni.getStorageSync('config_time'))
					if (tt != '0分') {
						this.readClick()
						
						return false
					} 
					this.wxad(bkdata)
					
					
					try {} catch (e) {
					uni.showToast({
						title: this.$t('book.sjyc'),
						icon: 'none'
					});
				}
			},
			customTruncate(str, maxSizeInMB, startByte) {
			  const maxBytes = maxSizeInMB * 1024 * 1024;
			    let totalBytes = 0;
			    let startIndex = 0;
			  
			    // 找到从 startByte 开始的起始索引
			    while (startIndex < str.length) {
			      const charCode = str.charCodeAt(startIndex);
			      const bytes = charCode < 0x0080 ? 1 : encodeURIComponent(str.charAt(startIndex)).replace(/%../g, 'x').length;
			      totalBytes += bytes;
			  
			      if (totalBytes >= startByte) {
			        break;
			      }
			  
			      startIndex++;
			    }
			  
			    // 从确定的索引开始截取数据
			    let endIndex = startIndex;
			    while (endIndex < str.length) {
			      const charCode = str.charCodeAt(endIndex);
			      const bytes = charCode < 0x0080 ? 1 : encodeURIComponent(str.charAt(endIndex)).replace(/%../g, 'x').length;
			  
			      if (totalBytes + bytes <= maxBytes) {
			        totalBytes += bytes;
			      } else {
			        break;
			      }
			  
			      endIndex++;
			    }
			  
			    return str.substring(startIndex, endIndex);
			},
			onChange(e) {
				this.$refs.popup.show();
				var that = this;
				that.Bookdata.list = []
				this.sqllist.forEach(async (res) => {
					await that.cso(res.search_url, res)
				});
			},
			async cso(search_url, data) {
				let that = this;
				let name = that.bkdata.name ? that.bkdata.name : that.Bookdata.source.book_name
				let header = {}
				if (data.header) {
					header = this.hesplic(data.header)
				}
				let url = search_url.replace("{{key}}", encodeURIComponent(name));
				
				this.zaiApi({
					url: url,
					header:header
				}).then(function(res) {
					that.cGetSearchData(res, data)
				});
			},
			cGetSearchData(res, data) {
				let that = this;
				_tool.searchData(res, data).then(function(res) {
					res.map((item, index) => {
					
						if (item.name+item.author === that.bkdata.name+that.bkdata.author) {
							that.Bookdata.list = that.Bookdata.list.concat(item)
						}
					});
					// console.log(that.Bookdata.list)
				});
			}
		}
	}
</script>

<style lang="less">
	.img-box {
		height: 320rpx;
		width: 220rpx;
	}
	.loader {
		
	  border: 2px solid rgba(79, 79, 79, 0.2);
	  border-left-color: #00000045;
	  border-radius: 50%;
	}
	
	.loader {
	  border: 2px solid rgba(79, 79, 79, 0.2);
	  border-left-color: #00000045;
	  width: 30px;
	  height: 30px;
	}
	
	.loader {
	  border: 2px solid rgba(79, 79, 79, 0.2);
	  border-left-color: #00000045;
	  width: 30px;
	  height: 30px;
	  animation: spin89345 1s linear infinite;
	}
	image {
		background-image: url('@/static/bakerBook.png');
		background-size: 100% 100%;
		background-position: 50% 50%;
		background-repeat: no-repeat;
		height: 320rpx;
	}

	.jh {
		color: #027ce1;
		margin-left: 30rpx;

	}

	.yuanba {
		background-color: #027ce1;
		color: #fff;
		padding: 20rpx;
	}

	.yuanname {
		position: relative;
		top: 0;
	}

	.zai-tabbar-bar {
		bottom: 0;
		width: 100%;
		position: fixed;
		z-index:9999
	}

	.text-sm {
		width: 600rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 1;
		-webkit-box-orient: vertical;
	}
	.cu-item {
		position: relative;
		padding: 30upx;
		height: 80upx;
		background-color: #ffffff;
		justify-content: flex-end;
		align-items: center
	}
	.item-wrap{
		border-bottom: 1px #eee dashed;
		padding-bottom: 10rpx;
	}
	.arrow:before {
	    position: absolute;
	    top: 0;
	    right: 30rpx;
	    bottom: 0;
	    display: block;
	    margin: auto;
	    width: 30rpx;
	    height: 30rpx;
	    color: #8799a3;
	    content: "\e6a3";
	    text-align: center;
	    font-size: 34rpx;
	    font-family: cuIcon;
	    line-height: 30rpx;
	    margin-top: auto;
	    margin-right: auto;
	    margin-bottom: auto;
	    margin-left: auto;
	}

</style>
